package com.ks.service;

import com.ks.base.BaseService;
import com.ks.dao.*;
import com.ks.entity.*;
import com.ks.util.Config;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service("depositoryService")
public class DepositoryService<T> extends BaseService<T> {
	private final static Logger log = Logger.getLogger(DepositoryService.class);

	@Autowired
	private DepositoryDao<T> dao;
	@Autowired
	private QuestionDao<T> questionDao;
	@Autowired
	private ContentDao<T> contentDao;
	@Autowired
	private QuestiontypeDao<T> questiontypeDao;
	@Autowired
	private ContentQuestionDao<T> contentQuestionDao;
	@Autowired
	private ProfessionDao<T> professionDao;
	@Autowired
	private RankDao<T> rankDao;
	@Autowired
	private PaperQuestiontypeDao<T> paperQuestiontypeDao;
	@Autowired
	private ContentQuestionService<T> contentQuestionService;
	@Autowired
	private StudentQuestionDao<T> studentQuestionDao;

	public DepositoryDao<T> getDao() {
		return dao;
	}

	/**
	 * 上传图片
	 * 
	 * @param file
	 * @return
	 */
	public String uploadImg(MultipartFile file, String pathStr) {
		String relativePath = "";
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String uuid = UUID.randomUUID().toString();
			String newFileName = uuid + "." + suffix;
			String filePath = Config.UPLOAD_PATH + File.separator + pathStr;
			File targetFile = new File(filePath, newFileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			relativePath = File.separator + "upload" + File.separator + pathStr + File.separator + newFileName;
		}
		return relativePath;
	}

	/**
	 * 跳转到章节页面
	 * 
	 * @param
	 * @param depId
	 */
	public Map<String, Object> toKnows(String depId) {
		Map<String, Object> resultMap = new HashMap<>();
		if (StringUtils.isNotBlank(depId) && !"0".equals(depId)) {

			ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
			Depository depository = (Depository) ac.getBean("depository");
			depository = (Depository) dao.queryById(depId);
			resultMap.put("depo", depository);
			// 查询专业
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("orderCondition", "");
			dataMap.put("mysqlQueryCondition", "");
			List<Profession> proList = (List<Profession>) professionDao.queryByList(dataMap);
			if (!proList.isEmpty()) {
				resultMap.put("proList", proList);
			}
			// 查询级别
			Map<String, Object> rankDataMap = new HashMap<>();
			rankDataMap.put("orderCondition", "");
			rankDataMap.put("mysqlQueryCondition", "");
			List<Rank> rankList = (List<Rank>) rankDao.queryByList(rankDataMap);
			if (!rankList.isEmpty()) {
				resultMap.put("rankList", rankList);
			}
			// 查询章节信息
			Map<String, Object> map = new HashMap<>();
			map.put("depId", Integer.parseInt(depId));
			List<Content> conList = contentDao.queryByListDep(map);
			Map<String, Object> mapContent = new HashMap<>();
			int count = 0;
			for (Content content : conList) {
				mapContent.put("content_id",content.getId());
				int temp = contentQuestionDao.queryByCount(mapContent);
				content.setExtend(temp+"");
				count = count + temp;
			}
			resultMap.put("depId", depId);
			resultMap.put("conList", conList);
			resultMap.put("count", count);
		}
		return resultMap;
	}

	/**
	 * 根据专业获取级别
	 * 
	 * @param proId
	 * @return
	 */
	public Map<String, Object> getRanksByPro(String proId) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int status = 1;
		dataMap.put("proId", proId);
		List<Rank> rankList = (List<Rank>) rankDao.queryListByPro(dataMap);
		if (!rankList.isEmpty()) {
			resultMap.put("rankList", rankList);
		} else {
			status = 0;
		}
		resultMap.put("status", status);

		return resultMap;
	}

	/**
	 * 添加试题
	 * 
	 * @param size
	 * @param answer
	 * @param ansStr
	 * @param title
	 * @param description
	 * @param typeId
	 * @param type
	 * @param conId
	 * @param request
	 * @return
	 */
	@Transactional
	public Map<String, Object> addQuestion(String size, String answer, String ansStr, String title, String description,
			String typeId, String type, String conId, HttpServletRequest request, MultipartFile picture,
			MultipartFile ana_picture) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		
		// 根据typeId查询试题类型
		/*
		 * Questiontype qtype = null; try { qtype =
		 * questiontypeService.queryById(typeId); } catch (Exception e1) { //
		 * TODO 自动生成的 catch 块 e1.printStackTrace(); }
		 */

		Integer newQuestionId = null;
		Map<String, Object> map = new HashMap<String, Object>();
		String msg = "";
		String relativePicturePath = "";
		String relativeANAPicturePath = "";

		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Question question = (Question) ac.getBean("question");

		question.setTitle(title);
		question.setQuestiontype_id(Integer.parseInt(typeId));
		question.setAnalysis(description);
		question.setType(type);
		question.setCreatetime(new Date());

		if (!picture.isEmpty()) {
			relativePicturePath = uploadImg(picture, "question");
		}
		if (!ana_picture.isEmpty()) {
			relativeANAPicturePath = uploadImg(ana_picture, "question");
		}

		question.setPicture(relativePicturePath);
		question.setAna_picture(relativeANAPicturePath);
		// 获取选项
		String answerStr = "";
		Integer optionSize = Integer.parseInt(size);
		
		a:for (int i = 0; i < optionSize; i++) {
			//设置选项
			String optionStr = (String) request.getParameter("dxxzt_xx"+i);
			// 设置选项图片
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("optionPicture" + i);
			String opPictureStr="";
			if (!file.isEmpty()) {
				 opPictureStr = uploadImg(file, "option");
			}
			if(i>3) {
				break a;
			}
			switch (i) {
			case 0:
				question.setA(optionStr);
				question.setApic(opPictureStr);
				break;
			case 1:
				question.setB(optionStr);
				question.setBpic(opPictureStr);
				break;
			case 2:
				question.setC(optionStr);
				question.setCpic(opPictureStr);
				break;
			case 3:
				question.setD(optionStr);
				question.setDpic(opPictureStr);
				break;
			}	
		}
		//设置答案

		if (StringUtils.isNotBlank(ansStr)) {
			String[] ansArray =ansArray = ansStr.split(",");
			String anrr = "";
			for(int i=0;i<ansArray.length;i++) {
				String anr = ansArray[i];
				switch (anr) {
				case "0":
					anrr="A";
					break;
				case "1":
					anrr="B";
					break;
				case "2":
					anrr="C";
					break;
				case "3":
					anrr="D";
					break;
				}
				answerStr = answerStr+anrr;
			}
		}else {
			switch (answer) {
			case "0":
				answerStr="A";
				break;
			case "1":
				answerStr="B";
				break;
			case "2":
				answerStr="C";
				break;
			case "3":
				answerStr="D";
				break;
			}
		}
		question.setAnswer(answerStr);
		map.put("status", 1);
		msg = "添加成功！";

		try {
			// 添加试题
			questionDao.add(question);
			newQuestionId = question.getId();

			ApplicationContext act = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
			ContentQuestion contentQuestion = (ContentQuestion) act.getBean("contentQuestion");

			// 添加试题和章节关联关系
			contentQuestion.setContent_id(Integer.parseInt(conId));
			contentQuestion.setQuestion_id(newQuestionId);
			contentQuestionDao.add(contentQuestion);
		
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			map.put("status", 0);
			msg = e.getMessage();
		}
		map.put("msg", msg);
		return map;
	}

	/**
	 * 查询试题类型相关
	 *
	 * @param conId
	 */
	public Map<String, Object> toCheckQuestions(String conId) {
		Map<String, Object> resultMap = new HashMap<>();
		List<Questiontype> quList = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		List<Map<String, Object>> typeList = new ArrayList<Map<String, Object>>();
		// 根据章节id查询章节信息
		ApplicationContext acti = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Content content = (Content) acti.getBean("content");
		if (StringUtils.isNotBlank(conId)) {
			content = (Content) contentDao.queryById(conId);
			resultMap.put("content", content);
		}
		// 查询试题类型列表
		map.put("orderCondition", "");
		map.put("mysqlQueryCondition", "");
		quList = (List<Questiontype>) questiontypeDao.queryByList(map);
		// 构建前台页面显示结构体
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> listMap = null;
		Integer typeNum = 0;
		dataMap.put("content_id", conId);
		for (Questiontype qt : quList) {
			dataMap.put("type_id", qt.getId());
			typeNum = contentQuestionDao.queryCountByIdType(dataMap);
			listMap = new HashMap<String, Object>();
			listMap.put("typeId", qt.getId());
			listMap.put("typeName", qt.getName());
			listMap.put("typeCount", typeNum);
			typeList.add(listMap);
		}
		resultMap.put("typeList", typeList);
		return  resultMap;
	}

	/**
	 * 查询试题相关
	 * 
	 * @param model
	 * @param typeId
	 * @param ConId
	 */
	public void toCheckQuestion(Model model, String typeId, String ConId, String page_num, String page_size,
			String typeCount, String questiontypeId, String keyword) {

		model.addAttribute("typeCount", typeCount);
		Integer offset = 0;
		Integer pageSize = 0;
		if (StringUtils.isNotBlank(page_num) && StringUtils.isNotBlank(page_size)) {
			Integer pageNum = Integer.parseInt(page_num);
			pageSize = Integer.parseInt(page_size);
			if (pageNum > 1) {
				offset = (pageNum - 1) * pageSize;
			} else {
				offset = 0;
			}
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("conId", ConId);
		dataMap.put("typeId", typeId);
		dataMap.put("keyword", keyword);
		dataMap.put("offset", offset);
		dataMap.put("page_size", pageSize);
		 List<Question> resultList =  questionDao.findByTypeIdAndConId(dataMap);
		model.addAttribute("resultList", resultList);
		Content cont = null;
		try {
			cont = (Content) contentDao.queryById(ConId);
			model.addAttribute("content", cont);
			model.addAttribute("typeId", typeId);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		// 根据typeId查询试题类型
		Questiontype qt = null;
		try {
			qt = (Questiontype) questiontypeDao.queryById(typeId);
			model.addAttribute("qutype", qt);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	public Map<String, Object> toCheckQuestionAjax(String typeId, String ConId, String page_num, String page_size) {
		Map<String, Object> finalresultMap = new HashMap<String, Object>();
		String msg = "操作成功！";
		Integer status = 1;
		Integer offset = 0;
		Integer pageSize = 0;
		if (StringUtils.isNotBlank(page_num) && StringUtils.isNotBlank(page_size)) {
			Integer pageNum = Integer.parseInt(page_num);
			pageSize = Integer.parseInt(page_size);
			if (pageNum > 1) {
				offset = (pageNum - 1) * pageSize;
			} else {
				offset = 0;
			}
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("conId", ConId);
		dataMap.put("typeId", typeId);
		dataMap.put("offset", offset);
		dataMap.put("page_size", pageSize);

		// 根据typeId查询试题类型
		Questiontype qt = null;
		try {
			qt = (Questiontype) questiontypeDao.queryById(typeId);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		// 根据章节id查询章节内容
		Content cont = null;
		try {
			cont = (Content) contentDao.queryById(ConId);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		// 根据章节id和题类型id查询题目
		 List<Question> resultList =  questionDao.findByTypeIdAndConId(dataMap);
		finalresultMap.put("status", status);
		finalresultMap.put("msg", msg);
		finalresultMap.put("resultList", resultList);
		return finalresultMap;
	}

	/**
	 * 跳转到更新试题页面
	 * 
	 * @param model
	 * @param questionId
	 */
	@Transactional
	public void toUpdateQuestion(Model model, String questionId) {
		String label = "edit";
		model.addAttribute("label", label);
		List<Questiontype> typeList = new ArrayList<Questiontype>();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderCondition", "");
		map.put("mysqlQueryCondition", "");

		// 查询试题类型列表
		try {
			typeList = (List<Questiontype>) questiontypeDao.queryByList(map);
			model.addAttribute("typeList", typeList);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
		}
		// 查询试题
		if (StringUtils.isNotBlank(questionId)) {
			Question edQuestion = null;
			try {
				edQuestion = (Question) questionDao.queryById(questionId);
				if (null != edQuestion) {
					if (null != edQuestion.getQuestiontype_id()) {
						Questiontype qutype = (Questiontype) questiontypeDao.queryById(edQuestion.getQuestiontype_id());
						if(qutype.getCode().equals("pd")) {
							model.addAttribute("edOpSize", 2);
						}else {
							model.addAttribute("edOpSize", 4);
						}
						model.addAttribute("quTypeEntity", qutype);
					}
				}
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			model.addAttribute("upQuestion", edQuestion);
			List<Map<String,Object>> optionList = new ArrayList<>();
			if(StringUtils.isNotBlank(edQuestion.getA())) {
				Map<String,Object> optionMap = new HashMap<>();
				optionMap.put("id", "A");
				optionMap.put("title", edQuestion.getA());
				String str = "";
				if (null!=edQuestion.getApic()) {
					str = edQuestion.getApic().replace("\\","\\/");
				}
				optionMap.put("picture",str);
				optionList.add(optionMap);
			}
			if(StringUtils.isNotBlank(edQuestion.getB())) {
				Map<String,Object> optionMap1 = new HashMap<>();
				optionMap1.put("id", "B");
				optionMap1.put("title", edQuestion.getB());
				String str = "";
				if (null!=edQuestion.getBpic()) {
					str = edQuestion.getBpic().replace("\\","\\/");
				}
				optionMap1.put("picture",str);
				optionList.add(optionMap1);
			}
			if(StringUtils.isNotBlank(edQuestion.getC())) {
				Map<String,Object> optionMap2 = new HashMap<>();
				optionMap2.put("id", "C");
				optionMap2.put("title", edQuestion.getC());
				String str = "";
				if (null!=edQuestion.getCpic()) {
					str = edQuestion.getCpic().replace("\\","\\/");
				}
				optionMap2.put("picture",str);
				optionList.add(optionMap2);
			}
			if(StringUtils.isNotBlank(edQuestion.getD())) {
				Map<String,Object> optionMap3 = new HashMap<>();
				optionMap3.put("id", "D");
				optionMap3.put("title", edQuestion.getD());
				String str = "";
				if (null!=edQuestion.getDpic()) {
					str = edQuestion.getDpic().replace("\\","\\/");
				}
				optionMap3.put("picture",str);
				optionList.add(optionMap3);
			}

			model.addAttribute("edOpList", optionList);
			
		}
	}

	/**
	 * 编辑试题
	 * 
	 * @param questionId
	 * @param size
	 * @param answer
	 * @param ansStr
	 * @param title
	 * @param description
	 * @param typeId
	 * @param type
	 * @param request
	 * @return
	 */
	public Map<String, Object> updateQuestion(String questionId, String size, String answer, String ansStr,
			String title, String description, String typeId, String type, HttpServletRequest request,
			MultipartFile picture, MultipartFile ana_picture) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		

		// 根据typeId查询试题类型
		/*
		 * Questiontype qtype = null; try { qtype =
		 * questiontypeService.queryById(typeId); } catch (Exception e1) { //
		 * TODO 自动生成的 catch 块 e1.printStackTrace(); }
		 */

		Map<String, Object> map = new HashMap<String, Object>();
		String msg = "";
		String relativePicturePath = "";
		String relativeANAPicturePath = "";

		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Question question = (Question) ac.getBean("question");
		if (StringUtils.isNotBlank(questionId)) {
			question.setId(Integer.parseInt(questionId));
		}
		question.setTitle(title);
		question.setQuestiontype_id(Integer.parseInt(typeId));
		question.setAnalysis(description);
		question.setType(type);
		question.setUpdatetime(new Date());
		if (!picture.isEmpty()) {
			relativePicturePath = uploadImg(picture, "question");
			question.setPicture(relativePicturePath);
		}
		if (!ana_picture.isEmpty()) {
			relativeANAPicturePath = uploadImg(ana_picture, "question");
			question.setAna_picture(relativeANAPicturePath);
		}
		
		String answerStr = "";
		Integer optionSize = Integer.parseInt(size);
		a:for (int i = 0; i < optionSize; i++) {
			//设置选项
			String optionStr = (String) request.getParameter("dxxzt_xx"+i);
			// 设置选项图片
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("optionPicture" + i);
			String opPictureStr="";
			if (!file.isEmpty()) {
				 opPictureStr = uploadImg(file, "option");
			}
			if(i>3) {
				break a;
			}
			switch (i) {
			case 0:
				question.setA(optionStr);
				question.setApic(opPictureStr);
				break;
			case 1:
				question.setB(optionStr);
				question.setBpic(opPictureStr);
				break;
			case 2:
				question.setC(optionStr);
				question.setCpic(opPictureStr);
				break;
			case 3:
				question.setD(optionStr);
				question.setDpic(opPictureStr);
				break;
			}	
		}
		if (StringUtils.isNotBlank(ansStr)) {
			String[] ansArray = ansStr.split(",");
			String anrr = "";
			for(int i=0;i<ansArray.length;i++) {
				String anr = ansArray[i];
				switch (anr) {
				case "0":
					anrr="A";
					break;
				case "1":
					anrr="B";
					break;
				case "2":
					anrr="C";
					break;
				case "3":
					anrr="D";
					break;
				}
				answerStr = answerStr+anrr;
			}
		}else {
			switch (answer) {
			case "0":
				answerStr="A";
				break;
			case "1":
				answerStr="B";
				break;
			case "2":
				answerStr="C";
				break;
			case "3":
				answerStr="D";
				break;
			}
		}
		question.setAnswer(answerStr);

		try {
			// 修改试题
			questionDao.updateBySelective(question);
			map.put("status", 1);
			msg = "修改成功！";
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			map.put("status", 0);
			msg = e.getMessage();
		}
		map.put("msg", msg);
		return map;
	}

	/**
	 * 导入试题
	 * 
	 * @param file
	 * @return
	 */
	@Transactional
	public Map<String, Object> importQuestions(MultipartFile file, String conId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer status = 1;
		String msg = "数据校验无误！";
		HSSFWorkbook wookbook = null;
		try {
			wookbook = new HSSFWorkbook(file.getInputStream());
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		if (null != wookbook) {
			int sheetNumber = wookbook.getNumberOfSheets();
			HSSFSheet sheet = null;
			String sheetName = "";
			String sheetTypeCode = "";
			int rows = 0;
			HSSFRow row = null;
			String title = "";// 题干
			String proCode = "";// 专业代码
			String rankCode = "";// 级别代码
			String typeCode = "";// 类型代码
			String type = "";// 难易代码
			String answer = "";// 正确答案
			String analyze = "";// 答案解析
			String option1 = ""; // 选项1
			String option2 = ""; // 选项2
			String option3 = ""; // 选项3
			String option4 = ""; // 选项4
			String option5 = ""; // 选项5
			String option6 = ""; // 选项6
			String[] answerArr = null;
			ApplicationContext acti = null;
			Question question = null;
			ContentQuestion cquestion = null;
			/*Option option = null;*/
			List<String> optionList = null;
			String answerId = "";
			Map<String, Object> codeMap = null;
			if (sheetNumber > 0) {
				a: for (int i = 0; i < sheetNumber; i++) {
					sheet = wookbook.getSheetAt(i);
					if (null == sheet) {
						status = 0;
						msg = "第" + (i + 1) + "个sheet页为空！";
						break;
					} else {
						sheetName = sheet.getSheetName();
						if (StringUtils.isNotBlank(sheetName)) {
							switch (sheetName) {
							case "单选题":
								sheetTypeCode = "dx";
								break;
							case "判断题":
								sheetTypeCode = "pd";
								break;
							case "多选题":
								sheetTypeCode = "dxx";
								break;
							default:
								status = 0;
								msg = "sheet页名称不规范，应该为单选题、判断题和多选题中的一种！";
								break;
							}
							rows = sheet.getLastRowNum();
							b: for (int j = 1; j <= rows; j++) {
								row = sheet.getRow(j);
								if (null != row) {
									title = getCellValue(row.getCell((short) 0));
									proCode = getCellValue(row.getCell((short) 1));
									rankCode = trimZero(getCellValue(row.getCell((short) 2)));
									typeCode = getCellValue(row.getCell((short) 3));
									if (!typeCode.equals(sheetTypeCode)) {
										status = 0;
										msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j
												+ "行数据试题类型与所属sheet页试题类型不符！";
										break a;
									}
									type = getCellValue(row.getCell((short) 4));
									answer = trimZero(getCellValue(row.getCell((short) 5)));
									analyze = getCellValue(row.getCell((short) 6));
									option1 = getCellValue(row.getCell((short) 7));
									option2 = getCellValue(row.getCell((short) 8));
									option3 = getCellValue(row.getCell((short) 9));
									option4 = getCellValue(row.getCell((short) 10));
									option5 = getCellValue(row.getCell((short) 11));
									option6 = getCellValue(row.getCell((short) 12));
									if (StringUtils.isEmpty(title) || StringUtils.isEmpty(proCode)
											|| StringUtils.isEmpty(rankCode) || StringUtils.isEmpty(typeCode)
											|| StringUtils.isEmpty(type) || StringUtils.isEmpty(answer)) {
										status = 0;
										msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j
												+ "行数据不能为空（题干，专业代码，级别代码，类型代码，难易程度，正确答案）!";
										break a;
									} else {

										// 判断难易程度是否是数字
										if (Integer.parseInt(type) != 1 && Integer.parseInt(type) != 2 && Integer.parseInt(type) != 3) {
											status = 0;
											msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j
													+ "行数据难易程度不合乎规范，应该为1或2";
											break a;
										}
										// 判断答案是否合乎规范，单选和多选
										if (typeCode.equals("dx") && answer.trim().length() > 1) {
											status = 0;
											msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j + "行数据答案不正确！";
											break a;
										} else if (typeCode.equals("pd") && answer.trim().length() > 1) {
											status = 0;
											msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j + "行数据答案不正确！";
											break a;
										}
										// 判断选项是否合乎规范
										if (typeCode.equals("dx")) {
											if (StringUtils.isNotBlank(option1) && StringUtils.isNotBlank(option2)
													&& StringUtils.isNotBlank(option3)
													&& StringUtils.isNotBlank(option4) && StringUtils.isBlank(option5)
													&& StringUtils.isBlank(option6)) {

											} else {
												status = 0;
												msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j
														+ "行数据选项不正确,单选题有四个选项！";
												break a;
											}
										} else if (typeCode.equals("pd")) {
											if (StringUtils.isNotBlank(option1) && StringUtils.isNotBlank(option2)
													&& StringUtils.isBlank(option3) && StringUtils.isBlank(option4)
													&& StringUtils.isBlank(option5) && StringUtils.isBlank(option6)) {

											} else {
												status = 0;
												msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j
														+ "行数据选项不正确,判断题有两个选项！";
												break a;
											}
										} else if (typeCode.equals("dxx")) {
											if (StringUtils.isNotBlank(option1) && StringUtils.isNotBlank(option2)
													&& StringUtils.isNotBlank(option3)
													&& StringUtils.isNotBlank(option4)) {
													//删了第五个
											} else {
												status = 0;
												msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中第" + j
														+ "行数据选项不正确,多选题有四个选项！";
												break a;
											}
										}

									}
								} else {
									status = 0;
									msg = "第" + (i + 1) + "个sheet【" + sheetName + "】中无有效数据！";
									break a;
								}
							}
						} else {
							status = 0;
							msg = "第" + (i + 1) + "个sheet页名称为空！";
							break a;
						}
					}
				}
			} else {
				status = 0;
				msg = "无sheet页！";
			}
			// 导入
			if (status == 1) {
				a: for (int i = 0; i < sheetNumber; i++) {//循环读取数据
					sheet = wookbook.getSheetAt(i);//获取每个Sheet表
					sheetName = sheet.getSheetName();//获得名字
					switch (sheetName) {
					case "单选题":
						sheetTypeCode = "dx";
						break;
					case "判断题":
						sheetTypeCode = "dp";
						break;
					case "多选题":
						sheetTypeCode = "dxx";
						break;
					}
					rows = sheet.getLastRowNum();
					b: for (int j = 1; j <= rows; j++) {
						optionList = new ArrayList<String>();
						row = sheet.getRow(j);
						title = getCellValue(row.getCell((short) 0));
						proCode = getCellValue(row.getCell((short) 1));
						rankCode = trimZero(getCellValue(row.getCell((short) 2)));
						typeCode = getCellValue(row.getCell((short) 3));
						type = getCellValue(row.getCell((short) 4));
						answer = trimZero(getCellValue(row.getCell((short) 5)));
						analyze = getCellValue(row.getCell((short) 6));
						option1 = getCellValue(row.getCell((short) 7));
						option2 = getCellValue(row.getCell((short) 8));
						option3 = getCellValue(row.getCell((short) 9));
						option4 = getCellValue(row.getCell((short) 10));
						option5 = getCellValue(row.getCell((short) 11));
						option6 = getCellValue(row.getCell((short) 12));
						//保存到新表
						acti = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
						question = (Question) acti.getBean("question");
						question.setTitle(title);//题干
						question.setType(type);//难易度
						question.setAnswer(answer);//答案
						question.setA(option1);//选项1
						question.setB(option2);//选项2
						if(!"pd".equals(typeCode)){
							question.setC(option3);//选项3
							question.setD(option4);//选项4
						}
						//判断什么类型放什么id
						if("pd".equals(typeCode)){
							question.setQuestiontype_id(3);
						}
						if("dx".equals(typeCode)){
							question.setQuestiontype_id(1);
						}
						if("dxx".equals(typeCode)){
							question.setQuestiontype_id(2);
						}
						question.setAnalysis(analyze);
						questionDao.add(question);
						ContentQuestion cq = new ContentQuestion();
						cq.setContent_id(Integer.parseInt(conId));
						cq.setQuestion_id(question.getId());
						contentQuestionDao.add(cq);
						// 保存试题
						/*
						question.setTitle(title);
						question.setType(type);
						Map<String, Object> typeIdMap = questiontypeDao.queryIdByCode(typeCode);
						if (!typeIdMap.isEmpty()) {
							Integer typeId = Integer.parseInt(typeIdMap.get("typeId").toString());
							question.setQuestiontype_id(typeId);
						}
						question.setAnalysis(analyze);
						question.setCreatetime(new Date());
						questionDao.add(question);
						// 保存试题和章节关联关系
						cquestion = (ContentQuestion) acti.getBean("contentQuestion");
						cquestion.setContent_id(Integer.parseInt(conId));
						cquestion.setQuestion_id(question.getId());
						contentQuestionDao.add(cquestion);
						// 保存选项
						if ("dx".equals(typeCode)) {
							optionList.add(option1);
							optionList.add(option2);
							optionList.add(option3);
							optionList.add(option4);
						} else if ("pd".equals(typeCode)) {
							optionList.add(option1);
							optionList.add(option2);
						} else if ("dxx".equals(typeCode)) {
							optionList.add(option1);
							optionList.add(option2);
							optionList.add(option3);
							if (StringUtils.isNotBlank(option4)) {
								optionList.add(option4);
							}
						}*/

						/*if ("dxx".equals(typeCode)) {
							answerArr = answer.split(",");
							String answerIdStr = "";
							d: for (int l = 0; l < optionList.size(); l++) {

								acti = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
								option = (Option) acti.getBean("option");
								option.setQuestion_id(question.getId());
								option.setTitle(optionList.get(l));
								optionDao.add(option);
								e: for (int m = 0; m < answerArr.length; m++) {
									if ((l + 1) == Integer.parseInt(answerArr[m])) {
										answerIdStr = answerIdStr + option.getId().toString() + ",";
									}
								}
							}
							answerIdStr = answerIdStr.substring(0, answerIdStr.length() - 1);
							question.setAnswer(answerIdStr);
						} else {
							c: for (int k = 0; k < optionList.size(); k++) {
								acti = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
								option = (Option) acti.getBean("option");
								option.setQuestion_id(question.getId());
								option.setTitle(optionList.get(k));
								optionDao.add(option);
								if ((k + 1) == Integer.parseInt(answer)) {
									answerId = option.getId().toString();
								}
							}
							question.setAnswer(answerId);
						}*/
						// 更新试题答案项
						/*questionDao.updateBySelective(question);*/
						msg = "导入成功！";
					}
				}

			}
		}
		resultMap.put("status", status);
		resultMap.put("msg", msg);
		return resultMap;
	}

	/**
	 * 获得Hsscell内容
	 * 
	 * @param cell
	 * @return
	 */

	public String getCellValue(HSSFCell cell) {

		String value = "";

		if (cell != null) {
			switch (cell.getCellTypeEnum()) {

			case FORMULA:

				break;

			case NUMERIC:

				value = cell.getNumericCellValue() + "";

				break;

			case STRING:

				value = cell.getStringCellValue().trim();

				break;

			default:

				value = "";

				break;

			}

		}

		return value.trim();

	}

	String trimZero(String str) {

		if (StringUtils.isNotEmpty(str)) {
			return str.replace(".0", "");
		}
		return str;
	}

	public List<Depository> queryContents(Object o) {
		// TODO Auto-generated method stub
		return dao.queryContents(o);
	}

    public Map<String, Object> praticeIndex(User user) {
		Map<String, Object> map = new HashMap<>();
		List<Depository> list = (List<Depository>) dao.queryList(null);
		int countQuestion = 0;
        int countContent = 0;
        int countPractice = 0;//已练题数
		int correctCount = 0;//正确数量
		if (list.size()>0) {
            Depository entity = list.get(0);
            Map<String, Object> cmap = new HashMap<>();
            cmap.put("desp_id",entity.getId());
			map.put("img",entity.getPicture());
            List<Content> contentlist = (List<Content>) contentDao.queryList(cmap);
			countContent = contentlist.size();
            cmap.put("userId",user.getId());
            for (Content content : contentlist) {
				cmap.put("id",content.getId());
                countQuestion += contentQuestionService.findCountByContentId(content.getId());
				countPractice += studentQuestionDao.findCountJoinContent(cmap);
				correctCount += studentQuestionDao.findCountJoinContentCorrect(cmap);
            }
        }
		map.put("correctCount",correctCount);
		map.put("countPractice",countPractice);
		map.put("depositorylist",list);
        map.put("countQuestion",countQuestion);
        map.put("countContent",countContent);
		return map;
    }
}
